package responsibility;

import org.apache.ibatis.plugin.Plugin;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * 责任链模式
 *
 * @author Caleb
 * @date 2021/3/25 10:40
 * @description
 */
public class Main {

  interface Interceptor {
      Object plugin(Object target);

      Object doFilter(Object target, InterceptorChain chain);

  }

  static class InterceptorA implements Interceptor {

    @Override
    public Object plugin(Object target) {
      System.out.println("InterceptorA");
      return target;
    }

    @Override
    public Object doFilter(Object target, InterceptorChain chain) {
      System.out.println("过滤器InterceptorA执行前");
      chain.execute();
      System.out.println("过滤器InterceptorA执行后");
      return target;
    }
  }

  static class InterceptorB implements Interceptor {

    @Override
    public Object plugin(Object target) {
      System.out.println("InterceptorB");
      return target;
    }

    @Override
    public Object doFilter(Object target, InterceptorChain chain) {
      System.out.println("过滤器InterceptorB执行前");
      chain.execute();
      System.out.println("过滤器InterceptorB执行后");
      return target;
    }
  }

  static class InterceptorC implements Interceptor {

    @Override
    public Object plugin(Object target) {
      System.out.println("InterceptorC");
      return target;
    }

    @Override
    public Object doFilter(Object target, InterceptorChain chain) {
      System.out.println("过滤器InterceptorC执行前");
      chain.execute();
      System.out.println("过滤器InterceptorC执行后");
      return target;
    }

  }

  /**
   * Interceptor 链
   */
  static class InterceptorChain {
    List<Interceptor> chain = new ArrayList();
    Iterator<Interceptor> iterator;


    public void add(Interceptor interceptor) {
      chain.add(interceptor);
    }

    // 链中有多少Interceptor执行多少
    public Object pluginAll(Object target) {
      for (Interceptor interceptor : chain) {
        System.out.println(target);
        target = interceptor.plugin(target);
      }
      return target;
    }

    public void execute(){
      if(iterator == null) {
        iterator = chain.iterator();
      }
      if(iterator.hasNext()){
        Interceptor next = iterator.next();
        iterator.remove();
        next.doFilter(next,this);
      }else{
        System.out.println("目标方法");
      }
    }


  }

  static class Executor {

  }

  public static void main(String[] args) {

    Executor executor = new Executor();

    InterceptorA interceptorA = new InterceptorA();
    InterceptorB interceptorB = new InterceptorB();
    InterceptorC interceptorC = new InterceptorC();

    InterceptorChain chain = new InterceptorChain();
    chain.add(interceptorA);
    chain.add(interceptorB);
    chain.add(interceptorC);

    // 对Executor 进行了加强
    chain.pluginAll(executor);

    chain.execute();



  }
}
